import re
import requests
import json
import time
import account_conf

def get_userinfo():#获取设备信息
    html = requests.get(r"http://translate.google.cn/translate_a/element.js?&cb=googleTranslate")
    html = html.text
    href = re.findall(r"href='([^']+)'",html)
    if len(href) != 0:
        wlanuserip = re.findall(r"wlanuserip=([^&]+)", href[0])[0]
        wlanacname = re.findall(r"wlanacname=([^&]+)", href[0])[0]
        ssid_nasip = re.findall(r"ssid=&nasip=([^&]+)", href[0])[0]
        snmpagentip_mac = re.findall(r"snmpagentip=&mac=([^&]+)", href[0])[0]
        wirelessv2_url = re.findall(r"t=wireless-v2&url=([^&]+)", href[0])[0]
        apmac_nasid = re.findall(r"apmac=&nasid=([^&]+)", href[0])[0]
        vid = re.findall(r"vid=([^&]+)", href[0])[0]
        port = re.findall(r"port=([^&]+)", href[0])[0]
        nasportid = re.findall(r"nasportid=([^&]+)", href[0])[0]
        data = {"wlanuserip":wlanuserip,"wlanacname":wlanacname,"ssid_nasip":ssid_nasip,"snmpagentip_mac":snmpagentip_mac,"wirelessv2_url":wirelessv2_url,"apmac_nasid":apmac_nasid,"vid":vid,"port":port,"nasportid":nasportid}
        href = href[0]
        return href,data

def login(url,userid,password):#登录
    info = get_userinfo()
    href = info[0]
    userinfo = info[1]
    headers = {
        'Host': url[6:],
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
        'Referer': href,
        'Connection': 'keep-alive',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    data = {
        'userId': userid,
        'password': password,
        'service': '',
        'queryString': 'wlanuserip%3D' + userinfo["wlanuserip"] + '%26wlanacname%3D' + userinfo["wlanacname"] + '%26ssid%3D%26nasip%3D' + userinfo["ssid_nasip"] + '%26snmpagentip%3D%26mac%3D' + userinfo["snmpagentip_mac"] + '%26t%3Dwireless-v2%26url%3D' + userinfo["wirelessv2_url"] + '%26apmac%3D%26nasid%3D' + userinfo["apmac_nasid"] + '%26vid%3D' + userinfo["vid"] + '%26port%3D' + userinfo["port"] + '%26nasportid%3D' + userinfo["nasportid"],
        'operatorPwd': '',
        'operatorUserId': '',
        'validcode': '',
        'passwordEncrypt': 'false',
    }
    login_url = url + "/eportal/InterFace.do?method=login"
    # getonlineuserinfo_url = url + "/eportal/InterFace.do?method=getOnlineUserInfo"
    response = requests.post(url=login_url, data=data, headers=headers)
    result = response.json()
    result_1 = json.dumps(response.json(), ensure_ascii=False)
    result1 = result_1.encode('ISO-8859-1')
    result1 = result1.decode('utf-8')
    if '"message": "密码不匹配，请输入正确的密码!"' in result1:
        return '账户错误'
    elif '"message": "你使用的账号已达到同时在线用户数量上限!"' in result1:
        return '你使用的账号已达到同时在线用户数量上限!'
    elif '"result": "success"' in result1:
        userIndex = str(result['userIndex'])
        account_conf.modify(sections="user",variable="userindex",value=userIndex)
        return "成功\n" + "userindex为：" + str(userIndex)
    else:
        return "失败"

def logout(url,userindex):#登出
    headers = {
        'Host': url[6:],
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
        'Referer': url + "/eportal/success.jsp?userIndex=" + userindex,
        'Connection': 'keep-alive',
        'Accept-Language': 'zh-CN,zh;q=0.9',
    }
    data = {
        "userIndex=":userindex
    }
    logout_url = url + "/eportal/InterFace.do?method=logout"
    response = requests.post(url=logout_url, data=data, headers=headers)
    result1 = json.dumps(response.json(), ensure_ascii=False)
    result1 = result1.encode('ISO-8859-1')
    result1 = result1.decode('utf-8')
    return result1


def verify(url):  # 验证
    try:
        r = requests.get(url)
        return True
    except:
        return False

def reconnection(account,href,userinfo):#重连
    url1 = 'https://www.baidu.com'
    url2 = account[2]
    account = account
    while (True):
        if not verify(url1):  # 判断是否联网
            if verify(url2):  # 判断是否在校园网范围内
                login(url=account[2],href=href,userid=account[0],password=account[1],userinfo=userinfo)
        time.sleep(5)